package com.huluobo.a2204kotlinjetpackdemo.lifecycle

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import com.huluobo.a2204kotlinjetpackdemo.R

class ADActivity : AppCompatActivity() {

    private lateinit var adViewModel: ADViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ad)

        val time = findViewById<TextView>(R.id.time)
        val cancel = findViewById<Button>(R.id.cancel)
        adViewModel = ViewModelProvider(this)[ADViewModel::class.java]

        //每当adManager创建的时候,都需要传入viewmodel保存的时间
        val adManager = ADManager(adViewModel)
        //观察者是ADManager,被观察者是当前的Activity(ComponentActivity 实现了LifecycleOwner接口,所以可以直接作为被观察者使用)
        //通过  lifecycle.addObserver(adManager) 产生订阅关系
        //观察则三要素已经齐全
        lifecycle.addObserver(adManager)

        adViewModel.timingResult.observe(this) {
            time.text = "广告剩余时间:${it / 1000}秒"
            if (it / 1000 <= 1) {
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
                finish()
            }
        }

        cancel.setOnClickListener {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        }
    }
}